package dxunderground.winampController.Server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import javax.swing.DefaultListModel;

import dxunderground.winampController.Common.GUI;
import dxunderground.winampController.Server.GUI.ButtonActions;

public class ServerThread implements Runnable {
	private Socket socket = null;
	private GUI gui;
	private ButtonActions buttonActions;
	private DefaultListModel listModel;

	public ServerThread(Socket socket, GUI gui, ButtonActions buttonActions, DefaultListModel listModel) {
		this.socket = socket;
		this.gui = gui;
		this.buttonActions = buttonActions;
		this.listModel = listModel;
		listModel.addElement(socket.getInetAddress());
	}

	public void run() {
		try {
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

			String inputLine;
			String[] outputLine;
			Protocol protocol = new Protocol(this.gui, this.buttonActions);

			while ((inputLine = in.readLine()) != null) {
				outputLine = protocol.processInput(inputLine);
				for (int i = 0; i < outputLine.length; i++) {
					out.println(outputLine[i]);
				}
				if (outputLine[0].equals("__END__")) {
					break;
				}
			}
			out.close();
			in.close();
			socket.close();
			this.listModel.removeElement(socket.getInetAddress());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}